<template>
  <div class="myCheckObject">
    <van-nav-bar
      :title="$route.meta.title"
      left-arrow
      :border="false"
      @click-left="clickLeft"
      class="nav-bar"
    >
      <template #right>
				<div @click.stop="handleReject">
					<van-icon name="cross" size="20"  />
					<span style="color: #fff; font-size: 20px;padding-right: 10px">驳回</span>
				</div>

				<div @click.stop="clickRight">
					<van-icon name="success" size="20"  />
					<span style="color: #fff; font-size: 20px">预览保存</span>
				</div>

      </template>
    </van-nav-bar>

    <div class="content">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <van-tag plain type="primary" style="margin: 10px 10px 10px 20px"
          >基本信息</van-tag
        >
      </div>
      <van-row gutter="20" type="flex" align="center">
        <van-col span="12">
          <van-field
            v-model="checkType"
            name="checkType"
            label="检验类型"
            input-align="center"
          >
            <template #input>
              <fixed-select v-model="checkType" :dataList="checkTypeArr" />
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field
            readonly
            clickable
            label="校对信息"
            v-model="sampleName"
            placeholder="请选择"
            input-align="center"
            @click="showSamplePicker = true"
            class="select-record"
          />
        </van-col>
        <van-col span="12" style="padding-right: 10px">
          <van-field
            readonly
            clickable
            v-model="value2Name"
            name="value2Name"
            label="报告模板"
            input-align="center"
            @click="showReport = true"
          >
          </van-field>
          <van-popup v-model="showReport" round position="bottom">
            <van-picker
              show-toolbar
              :columns="option2"
              @cancel="showReport = false"
              @confirm="onConfirm"
            />
          </van-popup>
        </van-col>
      </van-row>

      <div style="display: flex; align-items: center">
        <van-tag plain type="primary" style="margin: 10px 0px 10px 20px"
          >检验项目</van-tag
        >
        <!-- <div style="margin-left: 50px; display: flex; align-items: center">
          <span style="font-size: 20px; display: inline-block">报告：</span>
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="value2"
              :options="option2"
              label="报告"
              style="width: 500px"
              ref="reportText"
            />
          </van-dropdown-menu>
        </div> -->
      </div>

      <div class="checkItem">
        <van-list :finished="finished" finished-text="暂无数据">
          <van-cell
            title-class="custom-title"
            value-class="custom-value"
            label-class="custom-label"
            v-for="(v, i) in list"
            :key="i"
            :title="v.attributeName"
          >
            <template #label>
              <div>检验标准：{{ v.attributeStandard }}</div>
              <div>检验结果：{{ v.attributeValue }}</div>
              <div style="display: flex">
                <span>是否报告项：</span>
                <van-checkbox
                  v-model="v.isReportAttribute"
                  shape="square"
                ></van-checkbox>
                <span style="margin-left: 20px">是否通过：</span>
                <van-checkbox
                  v-model="v.checkPass"
                  shape="square"
                  @change="
                    !v.checkPass ? (v.checkMessage = '') : v.checkMessage
                  "
                ></van-checkbox>
              </div>
              <div
                style="display: flex; align-items: center"
                v-if="!v.checkPass"
              >
                <span>驳回意见：</span
                ><van-field
                  v-model="v.checkMessage"
                  style="width: 40%; border: 1px solid #ebedf0; padding: 0"
                />
              </div>
            </template>
          </van-cell>
        </van-list>
      </div>
      <div style="display: flex; align-items: center">
        <van-tag
          plain
          type="primary"
          style="
            margin: 10px 0px 10px 20px;
            display: inline-block;
            height: 24px;
          "
          >历史数据</van-tag
        >
        <div style="display: flex; margin-left: 50px; align-items: center">
          <span style="font-size: 20px; display: inline-block">标准：</span>
          <van-dropdown-menu style="display: inline-block" direction="up">
            <van-dropdown-item
              v-model="value3"
              :options="option3"
              label="报告"
              style="width: 500px"
            />
          </van-dropdown-menu>
        </div>
      </div>
      <div class="checkItem">
        <van-list :finished="hFinished" finished-text="暂无数据">
          <van-cell
            title-class="custom-title"
            value-class="custom-value"
            label-class="custom-label"
            v-for="(v, i) in hList"
            :key="i"
            :title="v.attributeName"
          >
            <template #label>
              <div>检验编号：{{ v.testID }}</div>
              <div>报告书编号：{{ v.reportID }}</div>
              <div>检验标准：{{ v.attributeStandard }}</div>
              <div>检验结果：{{ v.attributeValue }}</div>
              <div style="display: flex">
                <span>是否报告项：</span>
                <van-checkbox v-model="v.isReportAttribute" shape="square">
                </van-checkbox>
              </div>
            </template>
          </van-cell>
        </van-list>
      </div>
    </div>

    <van-popup
      v-model="showSamplePicker"
      position="bottom"
      round
      :style="{ height: '50%' }"
      :lock-scroll="false"
    >
      <van-cascader
        v-model="sampleValue"
        :options="sampleArr"
        @close="showSamplePicker = false"
        @finish="onSampleFinish"
        :field-names="sampleNames"
      />
    </van-popup>
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="userList"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>

    <van-popup
      v-model="showPdf"
      position="left"
      :style="{ width: '50%', height: '100%' }"
    >
      <div
        style="display: flex; justify-content: flex-end; margin: 20px 20px 0 0"
      >
        <van-button
          type="primary"
          size="small"
          @click="passCheckTest()"
          style="margin-right: 20px"
          >符合规定</van-button
        >
        <van-button
          type="warning"
          size="small"
          @click="rejectCheckTest()"
          style="margin-right: 20px"
          >不符合规定</van-button
        >
        <van-button type="info" size="small" @click="SaveCheckTest()"
          >保存确定</van-button
        >
      </div>
      <!-- <div id="reportPdf"></div> -->
			<HPDFViewer :path="pdfUrl" />
    </van-popup>
  </div>
</template>

<script type='text/ecmascript-6'>
import {
  NavBar,
  Icon,
  Cell,
  CellGroup,
  Button,
  Popup,
  Field,
  Calendar,
  Notify,
  List,
  Tag,
  Picker,
  Dialog,
  DropdownMenu,
  DropdownItem,
  Checkbox,
  cascader,
  Col,
  Row,
} from "vant";
import SelectOne from "@/components/SelectOne";
import FixedSelect from "@/components/FixedSelect";
import $ from "jquery";
import HPDFViewer from "@/components/HPDFViewer";
import { getTestTree, getTestStandardSelect } from "@/api/base";
import {
  getCheckBatchIdSelect,
  selectTestReports,
  getCheckTestAttributes,
  getExistCheckTestAttributes,
  saveReportAttributes,
  previewTestReport,
  saveCheckTest,
  SaveCheckTestResult,
	RejectCheckTest
} from "@/api/check";
import { to } from "@/utils";
import dayjs from 'dayjs';

export default {
  name: "myCheckObject",
  components: {
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [Notify.name]: Notify,
    [List.name]: List,
    [Tag.name]: Tag,
    [Picker.name]: Picker,
    [Dialog.name]: Dialog,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Checkbox.name]: Checkbox,
    [cascader.name]: cascader,
    [Col.name]: Col,
    [Row.name]: Row,
    SelectOne,
    FixedSelect,
		HPDFViewer
  },
  data() {
    return {
      token: "",
      checkType: "1", //检验类型
      checkTypeArr: [
        { value: 1, text: "样品检验" },
        { value: 2, text: "稳定性检验" },
      ],
			pdfUrl: '',
      sampleName: "", //合并后检验样品
      showSamplePicker: false,
      sampleArr: [],
      sampleValue: "",
      sampleNames: {
        text: "name",
        value: "code",
      },
      materialCode: "",
      loading: false,
      finished: false,
      hFinished: false,
      list: [],
      showPicker: false,
      userList: [],
      value1: "01",
      option1: [
        { text: "国内", value: "01" },
        // { text: "国外", value: "02" },
      ],
      showReport: false,
      value2: "",
      value2Name: "",
      option2: [],
      standardCode: "",
      option3: [],
      value3: "",
      testID: "",
      hList: [],
      reportID: "",
      showPdf: false,
      pdfh5: null,
      domain: "",
    };
  },
  watch: {
    value3(val) {
      if (val) {
        this.getExistCheckTestAttributes(val);
      }
    },
    checkType(val) {
      if (val) {
        this.getSampleData();
      }
    },
  },
  mounted() {
    this.token = localStorage.getItem("tokenKey");
    this.domain = localStorage.getItem("domain");
    this.getSampleData();
  },
  methods: {
    clickLeft() {
      this.$router.replace({ name: "home" });
    },
    async getSampleData() {
      var that = this;
      var queryParams = {
        pageModel: {
          Token: this.token,
          Type: this.checkType,
        },
      };
      const [err, res] = await to(getCheckBatchIdSelect(queryParams));
      if (err) return;
      var result = res.Result;
      if (result.length == 0) {
        this.sampleArr = [];
        this.sampleName = "";
      } else {
        this.dowhile(result);
        this.sampleArr = result;
      }
    },
    dowhile(b) {
      for (var i = 0; i < b.length; i++) {
        if (b[i].children && b[i].children.length > 0) {
          this.dowhile(b[i].children);
        } else {
          delete b[i].children;
        }
      }
    },
    onSampleFinish({ selectedOptions }) {
      this.value2 = "";
      this.value2Name = "";
      this.option2 = [];

      this.showSamplePicker = false;
      var len = selectedOptions.length;
      var toDetail = selectedOptions[len - 1];
      this.sampleName = toDetail.name;
      this.materialCode = toDetail.materialCode;
      this.testID = toDetail.code;
      this.reportID = toDetail.reportID;
      this.getItemList(toDetail.code);
      this.getRecordList(this.materialCode);
      this.getTestStandardSelect(this.materialCode);
    },
    getItemList(code) {
      var queryParams = { Token: this.token, Search: [code, ""] };
      getCheckTestAttributes(queryParams)
        .then((response) => {
          var result = response.Result.data;
          this.list = result;
          if (this.list.length == 0) {
            this.finished = true;
          }
        })
        .catch(() => {});
    },
    debounce(fn) {
      var that = this;
      var timer = null;
      return function () {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          fn();
          timer = null;
        }, 500);
      };
    },
    onConfirm(value) {
      this.value2Name = value.text;
      this.value2 = value.value;
      this.showReport = false;
    },
    getRecordList(code) {
      var queryParams = { queryModel: { Token: this.token, Code: code } };
      selectTestReports(queryParams)
        .then((response) => {
          var result = response.Result;
          if (result && result.length > 0) {
            this.option2 = result;
            // this.value2 = result[0].value;
          }
        })
        .catch(() => {});
    },
    getTestStandardSelect(code) {
      var queryParams = { queryModel: { Token: this.token, code: code } };
      getTestStandardSelect(queryParams)
        .then((response) => {
          var result = response.Result;
          if (result && result.length > 0) {
            result.map((item) => {
              item.value = item.id;
            });
            this.option3 = result;
            this.value3 = result[0].value;
          }
        })
        .catch(() => {});
    },
    getExistCheckTestAttributes(val) {
      var queryParams = {
        Token: this.token,
        Search: [this.testID, val],
      };
      getExistCheckTestAttributes(queryParams)
        .then((response) => {
          var result = response.Result.existData;
          this.hList = result;
          if (this.hList.length == 0) {
            this.hFinished = true;
          }
        })
        .catch(() => {});
    },
    addTestRecord() {
      Notify({ type: "danger", message: "暂无加测记录" });
      return false;
    },
    reportPreview() {
      var that = this;
      if (this.value2 == "") {
        Notify({ type: "danger", message: "请选择报告" });
        return false;
      }
      var tabArr = [];
      if (this.list.length > 0) {
        this.list.map((item) => {
          if (item.isReportAttribute) {
            tabArr.push({
              batchID: item.batchID,
              materialCode: item.materialCode,
              testID: item.testID,
              attributeCode: item.attributeCode,
            });
          }
        });
      }
      if (this.hList.length > 0) {
        this.hList.map((item) => {
          if (item.isReportAttribute) {
            tabArr.push({
              batchID: item.batchID,
              materialCode: item.materialCode,
              testID: item.testID,
              attributeCode: item.attributeCode,
            });
          }
        });
      }
			if(tabArr.length==0) return Notify({ type: "danger", message: "请选择检验项目" });
      var param1 = {
        Token: this.token,
        reportID: this.reportID,
        testReportAttributes: tabArr,
      };

      saveReportAttributes(param1)
        .then((response) => {
          if (response.ErrorCode == 0) {
            if (that.testID && that.testID != "") {
              this.getPreviewTestReport();
            }
          }
        })
        .catch(() => {});
    },
    getPreviewTestReport() {
      var param = {
        Token: this.token,
        testId: this.testID,
        reportCode: this.value2,
      };
      var that = this;
      previewTestReport(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            var path = response.Result.path;
            // that.getPdf(pdfUrl);
						if(!path) return Notify({ type: "danger", message: "附件不存在" });
            that.showPdf = true;
            that.pdfUrl = path;
          }
        })
        .catch(() => {
          Notify({ type: "danger", message: "附件不存在" });
        });
    },
    getPdf(pdfurl) {
      this.pdfh5 = true;
      this.$nextTick(() => {
        this.pdfh5 = new Pdfh5("#reportPdf", {
          pdfurl,
          lazy: true,
        });
      });
    },
		handleReject(){
			let rejectData = this.list.filter(item => item.checkPass == false);
			if (!rejectData.length) return Notify({ type: "warning", message: "请选择需要驳回的数据!" });
			// 判断需要驳回的数据是否都填了驳回意见，没填则不可以保存
			var rejectData1 = rejectData.filter(item => item.checkMessage == "");
			if (rejectData1.length) return Notify({ type: "warning", message: "请填写驳回意见!" });
			Dialog.confirm({
        message: "确认驳回吗?",
      }).then(() => {
				var nowTime = new Date();
				nowTime.setTime(nowTime.getTime());
				var reportDate = nowTime.getFullYear() + "-" + (nowTime.getMonth() + 1) + "-" + nowTime.getDate();
				let params = {
					testID: this.testID,
					Token: this.token,
					materialCode: this.materialCode,
					reportDate: reportDate,
					reportCode: this.value2,
					checkGoal: "01",
					ReportRemark: "",
					checks: rejectData
				}
				console.log('params',params)
        RejectCheckTest(params).then(res=>{
          if(res.ErrorCode == 0){
						this.sampleName = "";
            this.sampleValue = "";
            this.value2 = "";
            this.value3 = "";
            this.list = [];
            this.hList = [];
            this.sampleArr = [];
            this.showPdf = false;
            this.getSampleData();
          }
        
				});
      }).catch(() => {});
		},
    clickRight() {
      this.reportPreview();
    },
    passCheckTest() {
      var that = this;
      var param = {
        Token: this.token,
        TestID: this.testID,
        TestResult: "符合规定",
      };
      SaveCheckTestResult(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.getPreviewTestReport();
          }
        })
        .catch(() => {});
    },
    rejectCheckTest() {
      var that = this;
      var param = {
        Token: this.token,
        TestID: this.testID,
        TestResult: "不符合规定",
      };
      SaveCheckTestResult(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.getPreviewTestReport();
          }
        })
        .catch(() => {});
    },
    SaveCheckTest() {
      var nowTime = new Date();
      nowTime.setTime(nowTime.getTime());
      var reportData = nowTime.getFullYear() + "-" + (nowTime.getMonth() + 1) + "-" + nowTime.getDate();
      var param = {
        Token: this.token,
        testID: this.testID,
        materialCode: this.materialCode,
        totalPage: "",
        number: "45",
        checks: this.list,
        reportDate: reportData,
        reportCode: this.value2,
        checkGoal: "01",
      };
			console.log('param',param)
      saveCheckTest(param)
        .then((response) => {
          if (response.ErrorCode == 0) {
            this.sampleName = "";
            this.sampleValue = "";
            this.value2 = "";
            this.value3 = "";
            this.list = [];
            this.hList = [];
            this.sampleArr = [];
            this.showPdf = false;
            this.getSampleData();
          }
        })
        .catch((data) => {});
    },
  },
};
</script>

<style>
.van-dropdown-menu__bar {
  box-shadow: none;
  align-items: center;
}

.van-checkbox__icon .van-icon {
  width: 1em;
  height: 1em;
  line-height: 1em;
}
/* .history .van-field__control {
  width: 160px;
  border: 1px solid #ebedf0;
} */
</style>
<style scoped lang="less">
/deep/.van-dropdown-menu__item {
  margin-right: 10px;
  justify-content: flex-start;
  padding: 0.1rem 0 !important;
  height: 0.8rem;
  box-sizing: border-box;
}
.myCheckObject {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow-y: hidden;
  // color: #fff;
}
.content {
  height: calc(100% - 1rem);
  overflow: auto;
}
.handleContent {
  width: 100%;
}
.van-col-style {
  font-size: 0.36rem;
  color: #000;
  text-align: left;
  margin-top: 0.2rem;
}
.van-cell {
  overflow: inherit;
}
/deep/.van-dropdown-menu__title {
  width: 5.75rem;
  height: 0.66rem;
  line-height: 0.66rem;
  border: 1px solid #ddd;
  font-size: 0.34rem;
  text-align: center;
}
/deep/.van-dropdown-menu__title::after {
  display: none;
}
/deep/.van-checkbox__icon {
  font-size: 16px;
}
/deep/.van-button--small {
  height: 0.7rem;
}
.readonly /deep/.van-field__body {
  background: #ddd;
}
/deep/.van-cell {
  padding: 0.2rem 0.4rem;
}
/deep/.van-field__body {
  border-radius: 2px !important;
  border: 1px solid #ddd;
}
/deep/.van-cell {
  font-size: 0.32rem;
}
/deep/.van-cascader__header {
  height: 1rem;
}
/deep/.van-cascader__tabs.van-tabs--line .van-tabs__wrap {
  height: 1rem;
}
</style>